package org.dragonnova.business.web;

import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.dragonnova.business.common.Constants;
import org.dragonnova.business.model.User;
import org.dragonnova.business.model.User.Second;
import org.dragonnova.business.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.base.pub.util.TokenUtils;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> userLogin(HttpServletResponse resp,
			HttpSession session, String userName, String password)
			throws Exception {

		if (StringUtils.isEmpty(password) || StringUtils.isEmpty(userName)) {
			return packInfo(false, "请输入用户名或密码！登录");
		}
		User user = null;
		try {
			user = userService.getUserByName(userName);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
		if (user == null) {
			return packInfo(false, "用户不存在！登录");
		} else {
			String md5Pwd = DigestUtils.md5DigestAsHex(password.getBytes());
			if (user.getPassword().equals(md5Pwd)) {
				try {
					String token = TokenUtils.createToken(userName,
							DigestUtils.md5DigestAsHex(md5Pwd.getBytes()));
					user.setSessionId(token);
				} catch (Exception e) {
					e.printStackTrace();
					return warnException(e);
				}
				user.setPassword("");
				setLoginUser(session, user);
				return packData(user);
			} else {
				return packInfo(false, "密码错误！登录");
			}
		}
	}

	@RequestMapping("/updateUser")
	@ResponseBody
	public Map<String, Object> updateUser(HttpSession session, User user)
			throws Exception {
		User loginUser = getLoginUser(session);
		if (user == null) {
			return packInfo(false, "尚未登录，修改");
		}
		if (loginUser.getId() != user.getId() && loginUser.getGid() != 1) {
			return packInfo(false, "无权操作，修改");
		}
		if (user.getPassword() == null) {
			return packInfo(false, "请输入密码，修改");
		}
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword()
				.getBytes()));
		try {
			boolean success = userService.updateUser(user);
			if (success) {
				User newUser = userService.getUserByName(loginUser
						.getUsername());
				newUser.setPassword("");
				setLoginUser(session, newUser);
			}
			return packSaveInfo(success);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/findUser")
	@ResponseBody
	public Map<String, Object> findUser(HttpSession session, Integer id,
			String searchText) {
		try {
			if (getUserId(session, true) == -10) {
				return packData(userService.findUser(id, searchText));
			} else {
				return packInfo(false, "无权操作，查询");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/getLoginUser")
	public String getloginUser(HttpSession session,@RequestParam(value = "callback", required = true)String callback,Model model) {
		User user = getLoginUser(session);
		if (user == null) {
			model.addAttribute("data", "用户尚未登录");
			return Constants.THYMELEAF_TEMPLATE_LOGIN;
		} else {
			model.addAttribute("data", packData(user));
			return callback;
		}
	}

	@RequestMapping("/getLoginUserJson")
	@ResponseBody
	public Map<String, Object> getloginUser(HttpSession session) {
		User user = getLoginUser(session);
		if (user == null) {
			return packInfo(false, "尚未登录，查询");
		} else {
			return packData(user);
		}
	}
	
	@RequestMapping("/delUser")
	@ResponseBody
	public Map<String, Object> delUser(HttpSession session,
			@RequestParam(value = "id", required = true) Integer id) {
		if (getUserId(session, true) == -10) {
			try {
				boolean success = userService.delUser(id);
				return packDelInfo(success);
			} catch (Exception e) {
				e.printStackTrace();
				return warnException(e);
			}
		} else {
			return packInfo(false, "无权操作，删除");
		}
	}

	@RequestMapping("/checkUser")
	@ResponseBody
	public Map<String, Object> findUserByName(HttpSession session,
			String username) {
		if (StringUtils.isEmpty(username)) {
			return packInfo(false, "请输入用户名！注册");
		}
		User user = null;
		try {
			user = userService.getUserByName(username);
			if (user == null) {
				return packInfo(true, "帐号可注册");
			} else {
				return packInfo(false, "此帐号已存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/addUser")
	@ResponseBody
	public Map<String, Object> addUser(HttpSession session,
			@Validated(Second.class) User user, BindingResult result) {
		if (result.hasErrors()) {
			return bindingResult(result);
		}
		try {
			User userByName = userService.getUserByName(user.getUsername());
			if (userByName != null) {
				return packInfo(false, "用户名已存在，注册");
			}
			String md5Pwd = DigestUtils.md5DigestAsHex(user.getPassword()
					.getBytes());
			user.setPassword(md5Pwd);
			if (user.getWxopenid() == null)
				user.setWxopenid("");
			boolean success = userService.addUser(user);
			if (success && null != user.getId()) {
				user.setPassword("");
				String token = TokenUtils.createToken(user.getUsername(),
						DigestUtils.md5DigestAsHex(md5Pwd.getBytes()));
				user.setSessionId(token);
				setLoginUser(session, user);
				return packData(user);
			}
			return packInfo(false, "注册");
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/getLoginUsers")
	public String getLoginUsers(Model model,@RequestParam(value="callback",required=true)String callback) {
		try {
			Set<User> users = userService.getLoginUsers();
			model.addAttribute("data", packData(users));
			return callback;
		} catch (Exception e) {
			e.printStackTrace();
			return Constants.THYMELEAF_TEMPLATE_ERROR;
		}
	}
}
